<template>
  <div class="update-photo">
    <img :src="img" alt="" ref="img" />
    <div class="toolbar">
      <div class="cancel" @click="$emit('close')">取消</div>
      <div class="confirm" @click="onConfirm">完成</div>
    </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { updateUserPhoto } from '@/api/user'

export default {
  name: 'UpdatePhoto',
  components: {},
  props: {
    img: {
      type: [String, Object],
      required: true,
    },
  },
  data() {
    return {
      cropper: null,
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {
    const image = this.$refs.img
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: 'move',
      aspectRatio: 1,
      autoCropArea: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false,
      movable: true,
    })
  },
  methods: {
    onConfirm() {
      this.cropper.getCroppedCanvas().toBlob(async (blob) => {
        try {
          this.$toast.loading({
            message: '保存中...',
            forbidClick: true,
            duration: 0,
          })
          // console.log(blob)
          // 如果 接口文档要求Content-Type 是 multipart/form-data
          // 则你必须传递 form-data 对象
          const formData = new FormData()
          formData.append('photo', blob)
          const { data } = await updateUserPhoto(formData)
          console.log(data)
          this.$emit('close')
          this.$emit('updata-photo', data.data.photo)
          this.$toast.success('修改成功')
        } catch (err) {
          this.$toast.fail('修改失败')
        }
      })
    },
  },
}
</script>
<style lang='less' scoped>
.update-photo {
  background-color: #000;
  height: 100%;
  .toolbar {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-between;
  }
  .cancel,
  .confirm {
    width: 90px;
    height: 90px;
    font-size: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #fff;
  }
}
.img {
  max-width: 100%;
  display: block;
}
</style>
